<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.bookmanager.model.User" %>
<%@ page import="java.util.List" %>
<%
    // 检查管理员权限
    User user = (User) session.getAttribute("user");
    if (user == null || !"admin".equals(user.getRole())) {
        response.sendRedirect("../login.jsp");
        return;
    }

    // 获取用户列表
    List<User> users = (List<User>) request.getAttribute("users");
%>
<html>
<head>
    <title>权限管理 - 图书管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f7fa;
            color: #333;
        }

        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 0 20px;
        }

        .nav-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            height: 70px;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }

        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .admin-badge {
            background: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .logout-btn {
            padding: 8px 16px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 0.9rem;
        }

        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .page-title {
            font-size: 1.8rem;
            color: #333;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .user-table {
            width: 100%;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .user-table th,
        .user-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .user-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #555;
            border-bottom: 2px solid #e9ecef;
        }

        .user-table tr:hover {
            background: #f8f9fa;
        }

        .role-admin {
            color: #dc3545;
            font-weight: bold;
            background: #f8d7da;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .role-reader {
            color: #28a745;
            font-weight: bold;
            background: #d4edda;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .search-box {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .search-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.2);
        }

        .close {
            float: right;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            color: #666;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }

        select.form-control {
            height: 40px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .empty-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="nav-bar">
        <div class="logo">📚 图书管理系统</div>
        <div class="admin-info">
            <span>欢迎，<strong><%= user.getUsername() %></strong></span>
            <span class="admin-badge">管理员</span>
            <a href="<%= request.getContextPath() %>/logout" class="logout-btn">退出登录</a>
        </div>
    </div>
</div>

<div class="container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">🔐 权限管理</h1>
        <div>
            <a href="../admin/dashboard.jsp" class="btn btn-secondary">返回控制台</a>
        </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
        <input type="text" id="searchInput" class="search-input" placeholder="搜索用户ID或用户名...">
        <button class="btn btn-primary" onclick="searchUsers()">🔍 搜索</button>
        <button class="btn btn-secondary" onclick="resetSearch()">显示全部</button>
    </div>

    <!-- 用户权限表格 -->
    <% if (users != null && !users.isEmpty()) { %>
    <div style="overflow-x: auto;">
        <table class="user-table">
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>当前角色</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="userTableBody">
            <% for (User u : users) { %>
            <tr>
                <td><%= u.getUserId() %></td>
                <td><strong><%= u.getUsername() %></strong></td>
                <td><%= u.getEmail() != null ? u.getEmail() : "未设置" %></td>
                <td>
                <span class="role-<%= u.getRole() %>">
                    <%= "admin".equals(u.getRole()) ? "管理员" : "普通用户" %>
                </span>
                </td>
                <td><%= u.getCreateTime() != null ? u.getCreateTime().toLocalDate().toString() : "未知" %></td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-warning btn-sm"
                                onclick="editUserRole('<%= u.getUserId() %>', '<%= u.getUsername() %>', '<%= u.getRole() %>')">
                            编辑权限
                        </button>
                    </div>
                </td>
            </tr>
            <% } %>
            </tbody>
        </table>
    </div>
    <% } else { %>
    <div id="emptyState" class="empty-state">
        <div class="empty-icon">👥</div>
        <h3>暂无用户数据</h3>
        <p>系统中还没有注册用户</p>
    </div>
    <% } %>
</div>

<!-- 编辑权限模态框 -->
<div id="editRoleModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeEditModal()">&times;</span>
        <h2 style="margin-bottom: 20px;">编辑用户权限</h2>

        <form id="roleForm">
            <input type="hidden" id="editUserId" name="userId">

            <div class="form-group">
                <label class="form-label">用户ID</label>
                <input type="text" id="editUserDisplayId" class="form-control" readonly>
            </div>

            <div class="form-group">
                <label class="form-label">用户名</label>
                <input type="text" id="editUsername" class="form-control" readonly>
            </div>

            <div class="form-group">
                <label class="form-label">角色</label>
                <select id="editRole" name="role" class="form-control" required>
                    <option value="reader">普通用户</option>
                    <option value="admin">管理员</option>
                </select>
            </div>

            <div style="display: flex; gap: 10px; margin-top: 25px;">
                <button type="submit" class="btn btn-primary" style="flex: 1;">更新权限</button>
                <button type="button" class="btn btn-secondary" onclick="closeEditModal()">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 搜索用户（前端过滤）
    function searchUsers() {
        const searchInput = document.getElementById('searchInput');
        const keyword = searchInput.value.toLowerCase().trim();
        const rows = document.querySelectorAll('#userTableBody tr');
        const emptyState = document.getElementById('emptyState');
        const table = document.querySelector('.user-table');

        let hasVisibleRows = false;

        rows.forEach(row => {
            const userId = row.cells[0].textContent.toLowerCase();
            const username = row.cells[1].textContent.toLowerCase();
            const email = row.cells[2].textContent.toLowerCase();

            if (userId.includes(keyword) || username.includes(keyword) || email.includes(keyword)) {
                row.style.display = '';
                hasVisibleRows = true;
            } else {
                row.style.display = 'none';
            }
        });

        // 显示/隐藏空状态
        if (emptyState) {
            if (!hasVisibleRows && keyword !== '') {
                emptyState.style.display = 'block';
                if (table) table.style.display = 'none';
            } else {
                emptyState.style.display = 'none';
                if (table) table.style.display = 'table';
            }
        }
    }

    // 重置搜索
    function resetSearch() {
        const searchInput = document.getElementById('searchInput');
        const rows = document.querySelectorAll('#userTableBody tr');
        const emptyState = document.getElementById('emptyState');
        const table = document.querySelector('.user-table');

        searchInput.value = '';

        rows.forEach(row => {
            row.style.display = '';
        });

        if (emptyState) {
            emptyState.style.display = 'none';
        }
        if (table) {
            table.style.display = 'table';
        }
    }

    // 编辑用户权限
    function editUserRole(userId, username, currentRole) {
        document.getElementById('editUserId').value = userId;
        document.getElementById('editUserDisplayId').value = userId;
        document.getElementById('editUsername').value = username;
        document.getElementById('editRole').value = currentRole;
        document.getElementById('editRole').setAttribute('data-current-role', currentRole);

        document.getElementById('editRoleModal').style.display = 'block';
    }

    // 关闭编辑模态框
    function closeEditModal() {
        document.getElementById('editRoleModal').style.display = 'none';
        document.getElementById('roleForm').reset();
    }

    // 提交权限修改
    document.getElementById('roleForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const userId = document.getElementById('editUserId').value;
        const newRole = document.getElementById('editRole').value;
        const currentRole = document.getElementById('editRole').getAttribute('data-current-role');

        // 如果角色没有变化，直接关闭模态框
        if (newRole === currentRole) {
            alert('角色没有变化！');
            closeEditModal();
            return;
        }

        if (confirm(`确定要将用户 ${userId} 的权限修改为 ${newRole == 'admin' ? '管理员' : '普通用户'} 吗？`)) {
            // 发送Ajax请求到服务器更新权限
            const formData = new FormData();
            formData.append('userId', userId);
            formData.append('role', newRole);
            formData.append('action', 'updateRole');

            fetch('${pageContext.request.contextPath}/admin/user-management', {
                method: 'POST',
                body: new URLSearchParams({
                    userId: userId,
                    role: newRole,
                    action: 'updateRole'
                })
            })
                .then(response => {
                    if (response.ok) {
                        alert('权限更新成功！');
                        closeEditModal();
                        // 重新加载页面以更新数据
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        throw new Error('更新失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('权限更新失败，请重试！');
                });
        }
    });

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('editRoleModal');
        if (event.target === modal) {
            closeEditModal();
        }
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeEditModal();
        }
    });
</script>
</body>
</html>